using System.Windows.Forms;
using System.Text.RegularExpressions;
using WindowsLive.Writer.Api;

namespace WikiPediaPlugin
{
    [WriterPlugin("18d43e01-4549-4fde-8ca6-c7b4b7385fac", "WikiPedia Plugin",
        PublisherUrl = "http://scottisafooldev.spaces.live.com",
        Description = "Allows you to create a WikiPedia link from the highlighted text.", 
        ImagePath = "writer.png", 
        HasEditableOptions = true)]
    [InsertableContentSource("WikiPedia Link")]
    public class Plugin : ContentSource
    {
        PluginSettings settings;

        public override void Initialize(IProperties pluginOptions)
        {
            base.Initialize(pluginOptions);
            settings = new PluginSettings(pluginOptions);
        }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content)
        {
            string s = Regex.Replace(content, @"<(.|\n)*?>", string.Empty);
            s = s.Replace("\r", "");
            s = s.Replace("\n", "");
            string link = "";
            DialogResult result = DialogResult.OK;
            if (settings.ShowGUI || string.IsNullOrEmpty(s))
            {
                using (frmMain form = new frmMain(s, settings))
                {
                    result = form.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        link = form.Link;
                        s = form.LinkText;
                    }
                }
            }
            else
            {
                string wiki = settings.WikiCode(s);
                string lang = settings.languagecodes[settings.LanguageNumber];
                link = string.Format("<a href=\"http://{0}.wikipedia.org/wiki/{1}\" target=\"_blank\">{2}</a>", lang, wiki, s);
            }
            
            content = link;
            return result;
        }

        public override void EditOptions(IWin32Window dialogOwner)
        {
            frmOptions op = new frmOptions(settings);
            op.ShowDialog();
        }
    }
}
